<script setup>
import { ref, onMounted } from "vue";
import { reactive } from "vue";
import { ArrowLeftBold, DocumentAdd } from "@element-plus/icons-vue";
import { regionData } from "../../../../cityData.js";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import axios from "axios";
const router = useRouter();

console.log(regionData);

const newAddress = ref({
  address: { province: "", city: "", district: "", city_id: 0 },
  detail: "",
  id: 0,
  is_default: 0,
  phone: "",
  real_name: "",
});

const form = reactive({
  address: { province: "", city: "", district: "", city_id: 0 },
  detail: "",
  id: 0,
  is_default: 0,
  phone: "",
  real_name: "",
});

const options = regionData;

const selectedOptions = ref([]);

const addresses = ref([]);

const getAddressList = async () => {
  try {
    const res = await axios.get(`${apiUrl}/address/list?page=1&limit=200`, {
      headers: {
        "Authori-zation": `Bearer ${getToken()}`,
      },
    });

    if (res.data.status === 200) {
      addresses.value = res.data.data;
    }
  } catch (e) {}
};

const selectAddress = (index) => {
  addresses.value.forEach((address, i) => {
    address.is_default = i === index;
  });
};

// 是否显示添加
let showDrawer = ref(false);

// 添加地址
const addAddress = () => {
  selectedOptions.value = [];
  Object.assign(form, newAddress.value);
  showDrawer.value = true;
};

// 取消
const cancelClick = () => {
  showDrawer.value = false;
};

// 修改省市区
const handleChange = (val) => {
  const provinceCode = val[0];
  const cityCode = val[1];
  const districtCode = val[2];
  form.address.city_id = parseInt(districtCode);
  
  // 查找省份
  const province = options.find((item) => item.value === provinceCode);
  if (province) {
    form.address.province = province.label;
    
    // 查找城市
    if (province.children) {
      const city = province.children.find((item) => item.value === cityCode);
      if (city) {
        form.address.city = city.label;
        
        // 查找区县
        if (city.children) {
          const district = city.children.find((item) => item.value === districtCode);
          if (district) {
            form.address.district = district.label;
          }
        }
      }
    }
  }
};

const setDefault = async (index) => {
  try {
    const res = await axios.post(
      `${apiUrl}/address/default/set`,
      { id: addresses.value[index].id },
      {
        headers: {
          "Authori-zation": `Bearer ${getToken()}`,
        },
      }
    );

    addresses.value.forEach((item) => (item.is_default = 0));
    addresses.value[index].is_default = 1;
  } catch (e) {}
};

const saveAddress = async () => {
  if (form.real_name === "") {
    ElMessage({
      message: "请输入姓名",
      type: "warning",
    });
    return;
  }
  if (form.phone === "") {
    ElMessage({
      message: "请输入联系电话",
      type: "warning",
    });
    return;
  }
  if (form.address.city_id === 0) {
    ElMessage({
      message: "请选择地区",
      type: "warning",
    });
    return;
  }
  if (form.detail === "") {
    ElMessage({
      message: "请输入详细地址",
      type: "warning",
    });
    return;
  }
  try {
    const res = await axios.post(`${apiUrl}/address/edit`, form, {
      headers: {
        "Authori-zation": `Bearer ${getToken()}`,
      },
    });
    if (res.data.status === 200) {
      showDrawer.value = false;
      getAddressList();
    } else {
      ElMessage({
        message: res.data.msg,
        type: "warning",
      });
    }
  } catch (e) {
    console.error(e);
  }
};

// 根据 city_id 查找对应的省市区代码
const findCodesByCityId = (cityId, data = options, path = []) => {
  for (const item of data) {
    const currentPath = [...path, item.value];
    
    // 如果找到匹配的区县代码
    if (item.value === cityId.toString()) {
      return currentPath;
    }
    
    // 递归查找子级
    if (item.children && item.children.length > 0) {
      const result = findCodesByCityId(cityId, item.children, currentPath);
      if (result) {
        return result;
      }
    }
  }
  return null;
};

const editAddress = (address) => {
  const codes = findCodesByCityId(address.city_id);
  if (codes && codes.length >= 3) {
    selectedOptions.value = codes;
  } else {
    // 如果找不到，尝试根据名称查找
    selectedOptions.value = [];
  }
  
  form.address = {
    province: address.province,
    city: address.city,
    district: address.district,
    city_id: address.city_id,
  };
  form.id = address.id;
  form.detail = address.detail;
  form.is_default = address.is_default;
  form.phone = address.phone;
  form.real_name = address.real_name;
  showDrawer.value = true;
};

const deleteAddress = async (address) => {
  try {
    const res = await axios.post(
      `${apiUrl}/address/del`,
      { id: address.id },
      {
        headers: {
          "Authori-zation": `Bearer ${getToken()}`,
        },
      }
    );
    getAddressList();
  } catch (e) {}
};

onMounted(() => {
  getAddressList();
});
</script>

<template>
  <div class="addressBox">
    <!-- 地址管理 -->
    <div class="title">{{ $t("order.addressTitle") }}</div>
    <div class="addressContainer">
      <el-row :gutter="20" style="width: 100%">
        <el-col :span="6" v-for="(address, index) in addresses" :key="index">
          <div
            class="addressCard"
            :class="{ default: address.is_default }"
            @click="setDefault(index)"
            @dblclick.stop="editAddress(address)"
          >
            <div class="name">{{ address.real_name }}</div>
            <div class="phone">{{ address.phone }}</div>
            <div class="address">
              {{ address.province }}{{ address.city }}{{ address.district
              }}{{ address.detail }}
            </div>
            <span v-if="address.is_default" class="defaultTag">{{
              $t("order.acquiesce")
            }}</span>
            <div style="position: absolute; top: 55px; right: 10px">
              <el-icon :size="14" @click.stop="editAddress(address)"><Edit /></el-icon
              ><el-icon
                :size="14"
                style="margin-left: 10px"
                @click.stop="deleteAddress(address)"
                ><Delete
              /></el-icon>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="addNewCard" @click="addAddress">
            <el-icon :size="25" style="margin-top: 30px"><DocumentAdd /></el-icon>
            <div>{{ $t("order.addAddress") }}</div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>

  <el-drawer v-model="showDrawer" direction="btt" :size="460">
    <template #header>
      <div class="drawTitle">{{ $t("order.addAddress") }}</div>
    </template>
    <template #default>
      <el-form :model="form" label-width="auto" class="formBox">
        <el-form-item>
          <el-input :placeholder="$t('account.address1')" v-model="form.real_name" />
        </el-form-item>
        <el-form-item>
          <el-input :placeholder="$t('account.phone')" v-model="form.phone" />
        </el-form-item>
        <el-form-item>
          <el-cascader
            size="large"
            :options="options"
            v-model="selectedOptions"
            :placeholder="$t('account.address6')"
            @change="handleChange"
            style="width: 330px"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item>
          <el-input :placeholder="$t('account.address2')" v-model="form.detail" />
        </el-form-item>
        <el-form-item>
          <el-checkbox
            v-model="form.is_default"
            :label="$t('account.address3')"
            :true-value="1"
            :false-value="0"
            size="large"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveAddress" style="width: 100%">{{
            $t("account.address4")
          }}</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="cancelClick" style="width: 100%">{{
            $t("account.address5")
          }}</el-button>
        </el-form-item>
      </el-form>
    </template>
  </el-drawer>
</template>

<style scoped lang="scss">
.drawTitle {
  text-align: center;
  font-weight: bold;
  color: #000;
}
.addressBox {
  width: 900px;
  min-height: calc(100vh - 551px);
}
.title {
  font-weight: bold;
  margin-bottom: 20px;
}

.addressContainer {
  display: flex;
  gap: 20px;
  margin-top: 20px;

  .addressCard {
    width: 100%;
    border: 1px solid #ccc;
    padding: 20px 20px;
    text-align: left;
    position: relative;
    background-color: #fff;
    cursor: pointer;
    transition: border-color 0.3s ease;
    margin-bottom: 20px;

    .name {
      font-weight: bold;
      font-size: 20px;
      margin-bottom: 10px;
    }

    .phone {
      color: #444;
      margin-bottom: 20px;
    }

    .address {
      color: #444;
      max-width: 300px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    &.default {
      border-color: black;
    }

    .defaultTag {
      position: absolute;
      top: 0;
      right: 0;
      background-color: black;
      color: white;
      font-size: 12px;
      padding: 5px 15px;
    }

    &:hover {
      box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);
    }
  }

  .addNewCard {
    width: 100%;
    height: 129px;
    border: 1px solid #ccc;
    color: #aaa;
    text-align: center;
    padding: 10px;
    cursor: pointer;
    transition: background-color 0.3s ease;
    background-color: #f0f0f044;
    margin-bottom: 20px;
  }
}

.formBox {
  width: 330px;
  margin: 0 auto;
}

::v-deep .el-input__inner {
  height: 40px;
}

::v-deep .el-drawer__body {
  padding-top: 0;
}
</style>
